﻿using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace T4UtilityBelt.Utilities
{
    public static class StringExtension
    {
        internal static CodeDomProvider CodeDomProvider { get; set; }

        static StringExtension()
        {
            CodeDomProvider = new Microsoft.CSharp.CSharpCodeProvider();
        }

        public static String Format(Type type)
        {
            return ShortenTypeRef(CodeDomProvider.GetTypeOutput(new CodeTypeReference(type)));
        }

        public static String FormatIdentifier(this string identifier)
        {
            return CodeDomProvider.CreateEscapedIdentifier(identifier);
        }

        public static string FormatParameter(this string identifier)
        {
            return FormatIdentifier(CamelCase(identifier));
        }

        public static string FormatField(this string identifier)
        {
            return FormatIdentifier("_" + identifier);
        }

        public static string FormatType(this string identifier)
        {
            return FormatIdentifier("_" + identifier);
        }

        public static string CamelCase(this string identifier)
        {
            if (string.IsNullOrEmpty(identifier))
                return identifier;

            if (identifier.Length == 1)
                return identifier[0].ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant();

            return identifier[0].ToString(System.Globalization.CultureInfo.InvariantCulture).ToLowerInvariant() + identifier.Substring(1);
        }

        private static String ShortenTypeRef(String typeRef)
        {
            return (typeRef.LastIndexOf('.') != 6)
                        ? typeRef.Replace("System.Data.Linq.", "")
                        : typeRef.Replace("System.", "");
        }

        //private static string Format(CodeTypeReference codeTypeRef)
        //{
        //    return ShortenTypeRef(CodeDomProvider.GetTypeOutput(codeTypeRef));
        //}


    }
}
